<template>
  <view class="sms-verify-page">
    <!-- 导航栏 -->
    <up-navbar
      :border="false"
      bg-color="#f8f8f8"
      title-color="#333"
      @leftClick="goBack"
    >
      <template #center>
        <text class="nav-title">验证短信验证码</text>
      </template>
    </up-navbar>

    <!-- 主要内容 -->
    <view class="content">
      <!-- 验证码发送信息 -->
      <view class="verify-info">
        <text class="info-title">验证码已发送至</text>
        <view class="phone-info">
          <text class="phone-number">{{ phoneNumber }}</text>
          <text
            class="resend-btn"
            :class="{ active: countdown === 0 }"
            @click="resendCode"
          >
            {{ countdownText }}
          </text>
        </view>
      </view>

      <!-- 验证码输入框 -->
      <view class="code-input-container">
        <view class="code-inputs">
          <up-code-input v-model="correctCode" :maxlength="6"></up-code-input>
        </view>
      </view>
      <!-- 下一步按钮 -->
      <view class="next-button-container">
        <up-button
          type="primary"
          :disabled="!canProceed"
          :loading="isLoading"
          @click="handleLogin"
        >
          下一步
        </up-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import {
  ref,
  computed,
  onMounted,
  onUnmounted,
  defineEmits,
  defineProps,
} from "vue";

import { useUserStore } from "@/store/user";

import { showToast } from "@/utils/tools";

// 使用用户状态管理
const userStore = useUserStore();

const emit = defineEmits(["comfirm", "goback"]);

const props = defineProps({
  phoneNumber: {
    type: String,
    default: "",
  },
  countryCode: {
    type: String,
    default: "",
  },
});
// 倒计时
const countdown = ref(60);
const countdownTimer = ref(null);
const isLoading = ref(false);

// 模拟的正确验证码
const correctCode = ref("123456");

const countdownText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}s` : "重发";
});

// 计算属性
const canProceed = computed(() => {
  return correctCode.value && correctCode.value.length == 6;
});
//登录
const handleLogin = async () => {
  if (!canProceed.value) return;
  isLoading.value = true;
  try {
    const result = await userStore.loginWithSms({
      phone: props.phoneNumber,
      country: props.countryCode,
      code: correctCode.value,
    });
    if (result.code === 0) {
      showToast("登录成功", "success");
      // 获取用户信息
      const res = await userStore.getUserInfo();
      if (res.code === 0) {
        // 跳转到首页并刷新页面
        uni.reLaunch({
          url: "/pages/index/index",
        });
      } else {
        showToast(res.desc || "获取用户信息失败");
      }
    } else {
      showToast(result.desc || "登录失败");
    }
  } catch (error) {
    showToast("验证失败，请重试", "error");
  } finally {
    isLoading.value = false;
  }
};

// 重新发验证码
const resendCode = async () => {
  if (countdown.value > 0) return;
  // 重置状态
  clearCode();
  countdown.value = 60;
  startCountdown();
  isLoading.value = true;
  try {
    // 发送验证码
    const result = await userStore.sendSmsCode({
      phone: props.phoneNumber,
      countryCode: props.countryCode.trim(),
      type: 1,
    });
    if (result.code === 0) {
      showToast("验证码已发送", "success");
    } else {
      showToast(result.desc || "发送验证码失败", "error");
    }
  } catch (error) {
    showToast("发送验证码失败，请重试");
  } finally {
    isLoading.value = false;
  }
};

// 清空验证码
const clearCode = () => {
  correctCode.value = "";
};

const startCountdown = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
  countdownTimer.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(countdownTimer.value);
      countdownTimer.value = null;
    }
  }, 1000);
};

//返回
const goBack = () => {
  emit("goback");
};

// 生命周期
onMounted(() => {
  startCountdown();
});

onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
});
</script>

<style lang="scss" scoped>
.sms-verify-page {
  background-color: var(--bg-primary);
  display: flex;
  flex-direction: column;
  .nav-title {
    font-size: 36rpx;
    font-weight: 500;
  }
  .content {
    padding: 80rpx 32rpx 0;

    .verify-info {
      margin-bottom: 120rpx;
      font-size: 36rpx;
      font-weight: 600;
      .info-title {
        display: block;
        margin-bottom: 20rpx;
      }

      .phone-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .resend-btn {
          font-size: 32rpx;
          color: #999;
          padding: 12rpx 24rpx;
          border-radius: 8rpx;
          transition: all 0.3s;

          &.active {
            color: var(--primary-color);
            background: rgba(255, 140, 0, 0.1);
          }
        }
      }
    }
    .code-inputs {
      text-align: center;
    }

    .next-button-container {
      margin: 80rpx 0 40rpx;
    }
  }
}
</style>
